package cn.nkpro.elcube.cloud;

import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

@Activate(group = CommonConstants.PROVIDER)
public class NkCloudProviderFilter implements Filter {

    @Setter
    private UserDetailsService nkAccountService;

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try{
            RpcServiceContext context = RpcContext.getServiceContext();
            if(context!=null){
                Authentication authentication = (Authentication) context.getObjectAttachment("Authentication");
                String key = context.getAttachment("Authentication-Key");
                String secret = context.getAttachment("Authentication-Secret");

                if(authentication!=null){
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }else if(nkAccountService!=null && StringUtils.isNoneBlank(key,secret)){

                    UserDetails details = nkAccountService.loadUserByUsername(key.trim());
                    if(!StringUtils.equals(details.getPassword(),secret.trim())){
                        throw new BadCredentialsException("服务验证错误");
                    }

                    AbstractAuthenticationToken auth = new UsernamePasswordAuthenticationToken(details.getUsername(),null, details.getAuthorities());
                    auth.setDetails(details);
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            }
            return invoker.invoke(invocation);
        }finally {
            RpcServiceContext.removeContext();
        }
    }
}
